﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;

namespace MetroPivotWebPart.WebParts.MetroPivotWebPart
{
    public partial class MetroPivotWebPartUserControl : UserControl
    {
        private const string ClientResourceVersion = "1.0";

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            InitResources();
        }

        public bool ShowLastTab
        {
            get;
            set;
        }

        public string HeadingFontSize
        {
            get;
            set;
        }

        protected virtual void InitResources()
        {
            //prevent flicker of default layout before zone is 'enhanced'
            Page.ClientScript.RegisterClientScriptBlock(typeof(MetroPivotWebPartUserControl), "metro_initcss", "<style type=\"text/css\">.s4-wpTopTable { visibility: hidden; }</style>");

            //default CSS
            Page.ClientScript.RegisterClientScriptBlock(typeof(MetroPivotWebPartUserControl), "metro_css",
                string.Format("<link id=\"MetroPivotWebPart_CSS\" rel=\"stylesheet\" type=\"text/css\" href=\"{0}/_layouts/MetroPivotWebPart/MetroPivotWebPart.css?v={1}\" />",
                    SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/'),
                    ClientResourceVersion));
            
            Page.ClientScript.RegisterClientScriptBlock(typeof(MetroPivotWebPartUserControl), "jQuery", string.Format("<script type=\"text/javascript\">{0}</script>", 
                " typeof ($) != \"undefined\" || document.write('<script src=\"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js\">\\x3C/script>') "));

            RegisterJavascriptBlock(
                Page.ClientScript,
                string.Format("typeof($.metroPivotWebPart)!=\"undefined\" || document.write('<script src=\"{0}/_layouts/MetroPivotWebPart/jquery.MetroPivotWebPart{2}.js?v={1}\">\\x3C/script>');",
                    SPContext.Current.Site.RootWeb.ServerRelativeUrl.TrimEnd('/'),
                    ClientResourceVersion,
                    Minified ? ".min" : null));
        }

        private void RegisterJavascriptBlock(ClientScriptManager sm, string script)
        {
            string key = string.Format("MetroPivotWP_{0}", ClientResourceVersion);
            if (!sm.IsClientScriptBlockRegistered(key))
            {
                sm.RegisterClientScriptBlock(typeof(MetroPivotWebPartUserControl), key, string.Format("<script type=\"text/javascript\">{0}</script>", script));
            }
        }

        private bool Minified
        {
            get
            {
#if DEBUG
                return false;
#else
                return true;
#endif
            }
        }
    }
}
